﻿using System;

namespace STX.Lib.Security
{
    /// <summary>
    /// Session方式验证码管理器
    /// </summary>
    public class SessionSafeCodeManager : AbstractSafeCodeProvider
    {
        /// <summary>
        /// 根据SESSIONID获取SafeCode
        /// </summary>
        /// <param name="sessionid">SESSIONID</param>
        /// <returns></returns>
        public override string GetSafeCode( string sessionid )
        {
            if ( System.Web.HttpContext.Current != null &&
               System.Web.HttpContext.Current.Session != null &&
               System.Web.HttpContext.Current.Session["safecode"] != null )
            {
                return System.Web.HttpContext.Current.Session["safecode"].ToString();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 获取新验证码
        /// </summary>
        /// <param name="sessionid">SESSIONID</param>
        /// <returns></returns>
        public override string NewSafeCode( string sessionid )
        {
            string code = STX.Lib.Utils.Random.GetRandomString(4);
            System.Web.HttpContext.Current.Session["safecode"] = code;
            return code;
        }

        /// <summary>
        /// 清除验证码
        /// </summary>
        /// <param name="sessionid">SESSIONID</param>
        public override void ClearSafeCode( string sessionid )
        {
            if ( System.Web.HttpContext.Current != null &&
               System.Web.HttpContext.Current.Session != null &&
               System.Web.HttpContext.Current.Session["safecode"] != null )
            {
                System.Web.HttpContext.Current.Session["safecode"] = "";
            }
        }
    }
}